package org.azj.ImageEditor;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.azj.logHelper.LOG;
import org.azj.logHelper.LOG_COMPONENT;
import org.azj.logHelper.LOG_LEVEL;

class StreamGobbler extends Thread
{
    InputStream is;
    String type;
    
    StreamGobbler(InputStream is, String type)
    {
        this.is = is;
        this.type = type;
    }
    
    public void run()
    {
        try
        {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
                System.out.println(type + ">" + line);    
            } catch (IOException ioe)
              {
                ioe.printStackTrace();  
              }
    }
}

public class ImageEditor {
	// 保存文件新路径和就路径的map,key是新址，value是原路径
	private HashMap<String, String> imgPathMap;
	// 临时文件夹的位置
	private String tmpFolderPath;
	// 图片准备器
	private ImagePreparer imagePreparer;
	
	public ImageEditor() {
		imgPathMap = new HashMap<String, String>();
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		tmpFolderPath = null;
	}
	
	public void dispose() {
		delAllFile(tmpFolderPath);
		delFolder(tmpFolderPath);
	}
	
	private void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); //删除完里面所有内容
	        String filePath = folderPath;
	        filePath = filePath.toString();
	        java.io.File myFilePath = new java.io.File(filePath);
	        myFilePath.delete(); //删除空文件夹
	    } 
		catch (Exception e) {
			e.printStackTrace(); 
	    }
	}
	
	private void delAllFile(String path) {
		//删除tmpFolder下的所有文件
        File file = new File(path);
        if (!file.exists()) {
        	return;
        }
        if (!file.isDirectory()) {
        	return;
        }
        
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
        	if (tmpFolderPath.endsWith(File.separator)) {
        		temp = new File(path + tempList[i]);
        	} else {
        		temp = new File(path + File.separator + tempList[i]);
        	}
        	if (temp.isFile()) {
        		temp.delete();
        	}
        	if (temp.isDirectory()) {
        		delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
        		delFolder(path + "/" + tempList[i]);//再删除空文件夹
        	}
        }
	}
	
	public void setImageFolderPath(String imageFoldPath) {
		this.tmpFolderPath = imageFoldPath;
		imgPathMap.clear();
	}
	
	public void setImagePreparer(ImagePreparer imagePreparer) {
		this.imagePreparer = imagePreparer;
	}
	
	private void clearAll() {
		imgPathMap.clear();
	}
	
	public boolean showPictures(List<String> imgIdentifier) {
		// prepare images
		String newPath = "";
		for (String identifier : imgIdentifier) {
			try {
				newPath = imagePreparer.prepare(tmpFolderPath, identifier);
				imgPathMap.put(newPath, identifier);
			} catch (Exception e) {
				LOG.WriteLog(LOG_LEVEL.CRITICAL, LOG_COMPONENT.LOG_COMP_COMMON, e.getMessage());
				clearAll();
				return false;
			}
		}
		
		// using explorer.exe to show images
		if (newPath.isEmpty() == false) {
			Runtime runtime = Runtime.getRuntime(); 
			// remove the filename, only remaining the directory path
			String directoryPath = newPath.substring(0, newPath.lastIndexOf("\\"));
			String[] commandArgs={"RecursiView.exe", directoryPath};  
			try {
				Process process = runtime.exec(commandArgs);
				// any error message?
	            StreamGobbler errorGobbler = new 
	                StreamGobbler(process.getErrorStream(), "ERROR");            
	            
	            // any output?
	            StreamGobbler outputGobbler = new 
	                StreamGobbler(process.getInputStream(), "OUTPUT");
	                
	            // kick them off
	            errorGobbler.start();
	            outputGobbler.start();
				process.waitFor();
			} catch (Exception e) {
				String msg = 
						String.format("显示图片[%s]时出现错误, 错误信息是[%s]", 
								imgPathMap.get(newPath), e.getMessage());
				LOG.WriteLog(LOG_LEVEL.CRITICAL, LOG_COMPONENT.LOG_COMP_COMMON, msg);
				clearAll();
				return false;
			}
		}
			
		return true; 
	}
	
	public List<String> getMissingPictures() {
		File file = new File(tmpFolderPath);
		List<String> missingFiles = new ArrayList<String>(imgPathMap.values());
		
		File[] filelist = file.listFiles();		
		for (File tmpfile : filelist) {
			String filePath = tmpfile.getAbsolutePath();
			if (imgPathMap.containsKey(filePath)) {
				missingFiles.remove(imgPathMap.get(filePath));
			}
		}
	
		return missingFiles;
	}
}
